package com.xincheng.shuimalong.fragment;


import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.MainActivity;
import com.xincheng.shuimalong.activity.insurance.NewFriendActivity;
import com.xincheng.shuimalong.activity.insurance.SearchFriendActivity;
import com.xincheng.shuimalong.adapter.viewpager.InsuranceViewPagerAdapter;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.friend.ChatMessage;
import com.xincheng.shuimalong.fragment.insurance.ChatHistoryFragmet;
import com.xincheng.shuimalong.fragment.insurance.FriendFragment;
import com.xincheng.shuimalong.listener.OnMessageListener;
import com.xincheng.shuimalong.listener.OnSystemListener;
import com.xincheng.shuimalong.util.RongUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ContactNotificationMessage;

import static android.R.attr.fragment;
import static io.rong.message.ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE;
import static io.rong.message.ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE;
import static io.rong.message.ContactNotificationMessage.CONTACT_OPERATION_REQUEST;

/**
 * Created by xuhao on 2017/6/13.
 * 保友
 */

public class InsuranceFragment extends BaseFragment implements ViewPager.OnPageChangeListener, MainActivity
        .HistoryCallBack ,MainActivity.GroupCallBack{
    @BindView(R.id.insurance_tablayout)
    TabLayout insuranceTablayout;
    @BindView(R.id.insurance_viewpage)
    ViewPager insuranceViewpage;
    @BindView(R.id.tv_system_number)
    TextView tvSystemNumber;
    private List<Fragment> mFragments;
    private ChatHistoryFragmet chatHistoryFragmet;
    private FriendFragment friendFragment;
    private ConversationListFragment conversationListFragment;
    private int select;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            Message message= (Message) msg.obj;
            ContactNotificationMessage notificationMessage= (ContactNotificationMessage) message.getContent();
            switch (notificationMessage.getOperation()){
                case CONTACT_OPERATION_ACCEPT_RESPONSE:
                    //同意添加好友
                    if(friendFragment!=null){
                        friendFragment.getFriendList();
                    }
                    break;
                case CONTACT_OPERATION_REQUEST:
                    //申请添加好友
                    tvSystemNumber.setVisibility(View.VISIBLE);
                    break;
                case CONTACT_OPERATION_REJECT_RESPONSE:
                    //拒绝添加好友
                    break;
            }
            showToastMsg(notificationMessage.getMessage());
        }
    };
    @Override
    public int getFragmentLayoutId() {
        return R.layout.fragment_insurance;
    }

    private void initFragment() {
        if (mFragments == null) {
            mFragments = new ArrayList<>();
//            chatHistoryFragmet = ChatHistoryFragmet.newInstance();
            friendFragment=FriendFragment.newInstance();
            conversationListFragment= new ConversationListFragment();
            Uri uri = Uri.parse("rong://" + getContext().getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话，该会话聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//设置群组会话，该会话非聚合显示
                    .build();
            conversationListFragment.setUri(uri);  //设置 ConverssationListFragment 的显示属性
            mFragments.add(conversationListFragment);
            mFragments.add(friendFragment);
        }
    }

    @Override
    public void initData() {
        initFragment();
        insuranceTablayout.setupWithViewPager(insuranceViewpage);
        String[] homeListTitleArr = getResources().getStringArray(R.array.insurance_tab);
        InsuranceViewPagerAdapter adapter = new InsuranceViewPagerAdapter(getChildFragmentManager(), homeListTitleArr,
                mFragments);
        insuranceViewpage.setAdapter(adapter);
        insuranceViewpage.addOnPageChangeListener(this);
    }

    @Override
    public void addListener() {
//        ((MainActivity) getActivity()).registerHistoryCallBack(this);
        ((MainActivity)getActivity()).registerGroupCallBack(this);
        RongUtil.getInstances().setSystemMessage(new OnSystemListener() {
            @Override
            public void onMessage(Message message, int left) {
                if(message.getContent() instanceof ContactNotificationMessage){
                    android.os.Message msg=new android.os.Message();
                    msg.what=1;
                    msg.obj=message;
                    handler.sendMessage(msg);
                }
            }
        });
        RongUtil.getInstances().setMessageListener(new OnMessageListener() {
            @Override
            public void onMessage(final ChatMessage chatMessage, int left) {
                if(chatHistoryFragmet!=null){
                    chatHistoryFragmet.RushList();
                }
            }
        });
    }

    @OnClick({R.id.tv_add, R.id.search_layout, R.id.system_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add:
                ShowActivity.showActivity(getActivity(), SearchFriendActivity.class);
                break;
            case R.id.search_layout:
                ShowActivity.showActivity(getActivity(), SearchFriendActivity.class);
                break;
            case R.id.system_message:
                tvSystemNumber.setVisibility(View.GONE);
                ShowActivity.showActivityForResult(getActivity(), NewFriendActivity.class, RequestCodeKey.UP_GROUPLIST);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        select = position;
        if (position == 0) {
//            chatHistoryFragmet.RushList();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void loadHistory() {
        if(chatHistoryFragmet!=null){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    chatHistoryFragmet.RushList();
                }
            },200);
    }
    }

    @Override
    public void loadGroup() {
        if(friendFragment!=null){
            friendFragment.getFriendList();
        }
    }
}
